import Loadable from "react-loadable";

const routes = [
  {
    path: "/main",
    to: "/main/home",
    exact: true,
  },
  {
    path: "/main/home",
    component: () => import("../pages/Home"),
  },
  {
    path: "/main/adminsList",
    component: () => import("../pages/admins/AdminsList"),
  },
  {
    path: "/main/addAdmin",
    component: () => import("../pages/admins/AddAdmin"),
    roles: ["超级管理员"],
  },
  {
    path: "/main/updateAdmin",
    component: () => import("../pages/admins/UpdateAdmin"),
  },
  {
    path: "/main/carsList",
    component: () => import("../pages/cars/CarsList"),
  },
  {
    path: "/main/checkCar",
    component: () => import("../pages/cars/CarCheck"),
  },
  {
    path: "/main/usersList",
    component: () => import("../pages/users/UsersList"),
  },
  {
    path: "/main/checkUser",
    component: () => import("../pages/users/CheckUser"),
  },
  {
    path: "/main/ownersList",
    component: () => import("../pages/owners/OwnersList"),
  },
  {
    path: "/main/checkOwner",
    component: () => import("../pages/owners/CheckOwner"),
  },
  {
    path: "/main/addOwner",
    component: () => import("../pages/owners/AddOwner"),
  },
  {
    path: "/main/ordersList",
    component: () => import("../pages/OrderList"),
  },
  {
    path: "/main/orderDetail",
    component: () => import("../pages/OrderDetail"),
  },
  {
    path: "/main/remarkList",
    component: () => import("../pages/Remark/RemarkList"),
  },
  {
    path: "/main/RemarkChart",
    component: () => import("../pages/Remark/RemarkChart"),
  },
];

export default handleRoutes(routes);
function handleRoutes(routes) {
  if (!Array.isArray(routes)) return;
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  const role = (userInfo || {}).role;
  return routes
    .filter((obj) => !obj.roles || obj.roles.includes(role))
    .map((item) => {
      const { component, children } = item;
      if (Array.isArray(item.children) && item.children.length) {
        return {
          ...item,
          component: Loadable({
            loader: component,
            loading: <div>加载中.....</div>,
          }),
          children: handleRoutes(children),
        };
      }
      //判断component是否存在， 存在的话是重定向
      if (!component) {
        return item;
      }

      //不存在children
      return {
        ...item,
        component: Loadable({
          loader: component,
          loading: () => <div>加载中.....</div>,
        }),
      };
    });
}
